<template>
  <div>
    <div>
      <el-page-header @back="goBack" content="返回上一页"> </el-page-header>
    </div>
    信息上传添加及更新
    <div class="divMode">
      <el-form
        style="margin-top: 3%; text-align: center; width: 600px"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="50px"
        class="demo-ruleForm"
      >
        <el-form-item label="名称" prop="info">
          <el-input v-model="ruleForm.info"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="subId">
          <el-select v-model="ruleForm.subId" placeholder="请选择" class="sub">
            <el-option
              v-for="sub in subList"
              :key="sub.id"
              :label="sub.subName"
              :value="sub.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <div>
            <el-upload
              v-model="ruleForm.img"
              class="upload-demo"
              action="http://192.168.142.30:8081/tool/upload/"
              :on-preview="handlePreview1"
              :on-remove="handleRemove1"
              :before-remove="beforeRemove1"
              multiple
              :limit="3"
              :on-exceed="handleExceed1"
              :on-success="handleSuccess1"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
            <!-- <input type="file" @change="onFileChangeImg" />
            <button @click="uploadFiles(1)">上传</button> 
            192.168.142.30
            -->
          </div>
        </el-form-item>
        <el-form-item label="说明" prop="notes">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="ruleForm.notes"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="url" prop="url">
          <div>
            <el-upload
              class="upload-demo"
              action="http://192.168.142.30:8081/tool/upload/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="3"
              :on-exceed="handleExceed"
              :on-success="handleSuccess"
              v-model="ruleForm.url"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
            <!-- <input type="file" @change="onFileChangeVideo" />
            <button @click="uploadFiles(2)">上传</button> -->
          </div>
        </el-form-item>
        <el-form-item label="审核" prop="auditing">
          <div>
            <el-radio-group v-model="ruleForm.auditing">
              <el-radio v-model="auditing" :label="0">未审核</el-radio>
              <el-radio v-model="auditing" :label="1">审核通过</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <div>
            <el-radio-group v-model="ruleForm.status">
              <el-radio v-model="status" :label="0">公共</el-radio>
              <el-radio v-model="status" :label="1">专属</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { addInfo } from "@/api/info";
import { updateInfo } from "@/api/info";
import { getSubList } from "@/api/sub";
import { deleteFile } from "@/api/tool";
import router from "@/router";

//import axios from "axios";
export default {
  name: "AdminAddUpdate",
  data() {
    return {
      ruleForm: {
        info: "",
        url: "",
        img: "",
        notes: "",
        subId: "",
        auditing: "",
        status: 0,
      },
      subList: [],
      rules: {
        info: [{ required: true, message: "请输入名称", trigger: "blur" }],
        subId: [{ required: true, message: "请选择", trigger: "blur" }],
      },
      selectedFileImg: "",
      selectedFileVideo: "",
      nodes: "",
      auditing: 0,
      status: 0,
      subId: 1,
      upStatus: false,
    };
  },
  methods: {
    getSubs() {
      // 获得科目列表
      getSubList().then((res) => {
        if (res.code === 0) {
          this.subList = res.data;

          //console.log(this.ruleForm.subId);
        }
      });
    },
    // 提交表单
    submitForm(formName) {
      let routeId = this.$route.query.add;
      //console.log(routeId);

      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (routeId === undefined) {
            const update = {
              id: this.ruleForm.id,
              info: this.ruleForm.info,
              subId: this.ruleForm.subId,
              notes: this.ruleForm.notes,
              auditing: this.ruleForm.auditing,
              status: this.ruleForm.status,
            };
            //console.log(update);
            updateInfo(update).then((res) => {
              console.log(res);
              this.ruleForm = "";
              router.push("/Write");
            });
          }
          if (routeId === "add") {
            console.log("this.ruleForm===>", this.ruleForm);
            console.log("this.auditing===>", this.ruleForm.auditing);
            console.log("this.status===>", this.ruleForm.status);
            addInfo(this.ruleForm).then((res) => {
              console.log(res);
              this.ruleForm = "";
              router.push("/Write");
            });
          }
        } else {
          //console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    onFileChangeImg(e) {
      this.selectedFileImg = e.target.files[0];
      this.ruleForm.img = this.selectedFileImg.name;
    },
    onFileChangeVideo(e) {
      this.selectedFileVideo = e.target.files[0];
      this.ruleForm.url = this.selectedFileVideo.name;
    },
    // uploadFiles(e) {
    //   const formData = new FormData();
    //   if (e === 1) {
    //     formData.append("file", this.selectedFileImg);
    //   } else {
    //     formData.append("file", this.selectedFileVideo);
    //   }

    //   //192.168.142.30
    //   axios
    //     .post("http://192.168.142.30:8081/tool/upload/", formData, {
    //       headers: {
    //         "Content-Type": "multipart/form-data",
    //       },
    //     })
    //     .then((response) => {
    //       if (response.data.code === 0) {
    //         this.$message({
    //           message: "添加成功",
    //           type: "success",
    //         });
    //       } else {
    //         this.$message.error("上传失败");
    //       }
    //     })
    //     .catch((error) => {
    //       console.error(error);
    //     });

    //   // uploadFile(formData).then((res) => {
    //   //   console.log("uploadFile===>", res);
    //   //   if (res.code === 0) {
    //   //     console.log(res);
    //   //   }
    //   // });
    // },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      const filePath = {
        filePath: file.response.url,
      };
      deleteFile(filePath).then((res) => {
        console.log(res);
      });
    },
    handlePreview(file) {
      console.log("file==>", file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(response, file, fileList) {
      console.log("url===>", file);
      this.upStatus = false;
      // 上传成功后，设置文件名到表单数据
      //this.ruleForm.url = file.name;
      this.ruleForm.url = response.url;
      this.$message({
        showClose: true,
        message: "上传成功",
      });
      this.upStatus = true;
    },
    handleRemove1(file, fileList) {
      const filePath = {
        filePath: file.response.url,
      };
      deleteFile(filePath).then((res) => {
        console.log(res);
      });
    },
    handlePreview1(file) {
      console.log("file==>", file);
    },
    handleExceed1(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove1(file, fileList) {
      console.log("beforeRemove1==>", file);
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess1(response, file, fileList) {
      this.upStatus = false;
      console.log("img===>", file);
      console.log("img==response=>", response);
      // 上传成功后，设置文件名到表单数据
      //this.ruleForm.img = file.name;
      this.ruleForm.img = response.url;
      this.$message({
        showClose: true,
        message: "上传成功",
      });
      this.upStatus = true;
    },
    goBack() {
      this.$router.go(-1);
    },
  },
  created() {
    this.getSubs();
  },
  mounted() {
    this.ruleForm = this.$route.params;
    this.auditing = this.ruleForm.auditing;
    this.status = this.ruleForm.status;
    this.subId = this.ruleForm.subId;
    //console.log(this.$route.params);
    //this.ruleForm.pId = this.$route.params.pid;

    //console.log(this.ruleForm);
  },
};
</script>
<style scoped>
.divMode {
  display: flex;
  justify-content: center;
  align-items: center;
}
.sub {
  margin-right: 70%;
}
</style>
